

//
//  BAResource.m
//  BabyAlbum
//
//  Created by master on 17/2/16.
//  Copyright © 2017年 master. All rights reserved.
//

#import "BAResource.h"
#import <CommonCrypto/CommonDigest.h>

@implementation BAResource

//TODO : 使用MD5存在崩溃,先用uuid
+ (NSString *)md5HexDigest:(NSData *)data {
    
    NSUUID *uuid = [NSUUID UUID];
    return [uuid UUIDString];
//    unsigned char result[16];
//    //    CC_MD5(str,strlen(str), r);，改成了     CC_MD5(str, (CC_LONG)strlen(str), r);即可。
//    CC_MD5((__bridge const void *)(data),(CC_LONG)[data length], result); // This is the md5 call
//    return [NSString stringWithFormat:
//            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
//            result[0], result[1], result[2], result[3],
//            result[4], result[5], result[6], result[7],
//            result[8], result[9], result[10], result[11],
//            result[12], result[13], result[14], result[15]
//            ];
}

+ (NSString *)getResourceName:(id)resource {
    if([resource isKindOfClass:[UIImage class]]) {
        NSData *data = [NSData dataWithData:UIImagePNGRepresentation(resource)];
        return [BAResource md5HexDigest:data];
    } else  if([resource isKindOfClass:[AVURLAsset class]]){
        AVURLAsset *res = (AVURLAsset *)resource;
        NSData *data = [NSData dataWithContentsOfURL:res.URL];
        NSString *ext = [[res.URL.absoluteURL.absoluteString componentsSeparatedByString:@"."] lastObject];
        return [[BAResource md5HexDigest:data] stringByAppendingFormat:@".%@",ext];
    } else {
        return nil;
    }
}

+ (UIImage *)imageNamed:(NSString *)name {
    if(!name || !name.length) {
        return nil;
    }
    return [UIImage imageWithData:[NSData dataWithContentsOfFile:[self resourcePathName:name]]];
}

+ (AVURLAsset *)videoNamed:(NSString *)name {
    if(!name || !name.length) {
        return nil;
    }
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:[self resourcePathName:name] ] options:nil];
    if(!asset.playable) {
        asset = nil;
    }
    return asset;
}

+ (NSString *)writeResource:(BAAlbumItem *)resource {
    if([resource isKindOfClass:[BAAlbumImageItem class]]) {
        BAAlbumImageItem *res = (BAAlbumImageItem *)resource;
        if(!res.image) {
            NSLog(@"写入失败 error: image为空");
            return nil;
        }
        NSString *name = [BAResource getResourceName:res.image];
        NSString *path = [BAResource resourcePathName:name];
        NSError *error;
        [UIImageJPEGRepresentation(res.image, 1) writeToFile:path options:NSDataWritingAtomic error:&error];
        if(error) {
            NSLog(@"%@ 写入失败 error: %@",path,error);
            return nil;
        }
        return name;
    } else if([resource isKindOfClass:[BAAlbumVideoItem class]]){
        BAAlbumVideoItem *res = (BAAlbumVideoItem *)resource;
        if(!res.video) {
            NSLog(@"写入失败 error: Video为空");
            return nil;
        }
        NSString *name = [BAResource getResourceName:res.video];
        NSString *path = [BAResource resourcePathName:name];
        NSError *error;
        [[NSData dataWithContentsOfURL:res.video.URL] writeToFile:path options:NSDataWritingAtomic error:&error];
        if(error) {
            NSLog(@"%@ 写入失败 error: %@",path,error);
            return nil;
        }

        return name;
    } else {
        return nil;
    }
}

+ (NSString *)resourcePathName:(NSString *)name {
    NSString *filename = @"Resource";
    
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:filename];
    if(![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    return [path stringByAppendingPathComponent:name];
    
}

+ (void)deleteResource:(BAAlbumItem *) resource {
    [[NSFileManager defaultManager] removeItemAtPath:[self resourcePathName:resource.name] error:nil];
}
@end
